/**
 * Created by kevenfeng on 2017/9/26.
 */
var express = require('express');
var router = express.Router();
var path = require("path");
var dbCommon = require(path.join(__dirname, "..", "model", "dbCommon.js"));
var configParser = require('../model/config-parser.js');
var fs = require("fs");
var ArticleCategory = require('../core/articleCategory');
var Phrase = require('../core/phrase');
var Paragraph = require('../core/paragraph');
var Opreators = require('../core/operator');
var rightConfigPath = path.join(__dirname, "../model/ruleConfig.conf");
var Observer = require('../core/observe')
var Publish = require('../core/publish');
var Timer = require('../core/timer');
var log4js = require(path.resolve(__dirname, '../config/logger'));
var logger = log4js.getLogger('status');

function getRulesRight(data) {
    var rules = data.rules;
    var rulesNames = Object.keys(rules);
    // return data["rootRight"];
    for (var i = 0, j = rulesNames.length; i < j; i++) {
        if (data[rulesNames[i] + "Member"]) {
            var members = data[rulesNames[i] + "Member"];
            var membersKeys = Object.keys(members);
            for (var m = 0, n = membersKeys.length; m < n; m++) {
                // if (options.sUserName == members[membersKeys[m]] && options.iAccountId == membersKeys[m]) {
                    return data[rulesNames[i] + "Right"];
                // }
            }
        }
    }
    return {};
}
function checkCookie(request) {
  return new Promise(function (resolve, reject) {
	const sUserName = request.cookies['Admin-Token'].split(' ')[0] || ''
    if (sUserName) {
    	resolve(sUserName)
    } else {
    	reject(new Error('请登录'));
    }
//      logger.info(data, "龙虎榜接口数据");
  })
}
function timestampToTime(timestamp) {
	let date = new Date(timestamp * 1000);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
//	let Y = date.getFullYear() + '-';
//	let M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
//	let D = date.getDate() + ' ';
	let h = date.getHours();
	let m = date.getMinutes();
//	let s = date.getSeconds();
	return h + "时" + m + "分";
}
// 时间戳转换为月日
function timestampToMD(timestamp) {
	let date = new Date(timestamp * 1000);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
//	let Y = date.getFullYear() + '-';
	let M = (date.getMonth()+1 ) + '';
	let D = date.getDate() + '';
	// let h = date.getHours();
	// let m = date.getMinutes();
//	let s = date.getSeconds();
	return M + "月" + D + "日";
}
router.post('/getUrlRightList', function (req, res, next) {
	checkCookie(req).then(function (user) {
		console.log("登陆人：" + user)
	    var parser = new configParser({});
	    var content = parser.parseFile(rightConfigPath, "utf8");
//	    var options = {
//	        sUserName: sUserName,
//	        iAccountId: iAccountId
//	    }
//	    var urlGroups = getRulesRight(options, parser.data);
	    var urlGroups = getRulesRight(parser.data);
	    res.json({
	        ret: 0,
	        content: urlGroups,
	        msg: '登陆成功'
	    })
	}).catch(function (error) {
      	res.json({
            ret: -1,
            msg: error
        })
    })
//	const sUserName = req.cookies['Admin-Token'].split(' ')[0];
//  const iAccountId = req.cookies['postName'];
//  if (!sUserName || !iAccountId) {
//      res.json({
//          ret: -1,
//          msg: '账号密码为空'
//      })
//      return;
//  }
});


router.post('/getRightConfig', function (req, res, next) {
    var content = fs.readFileSync(rightConfigPath, "utf8");
    console.log(content);
    res.json({
        ret: 0,
        content: content,
        msg: '获取配置成功'
    })
});

router.post('/saveRightConfig', function (req, res, next) {
    var code = req.body.content;
    var content = fs.writeFileSync(rightConfigPath, code, "utf8")
    res.json({
        ret: 0,
        content: content,
        msg: '保存配置成功'
    })
});


/* post users listing. */
router.post('/getList', function (req, res, next) {
    var reqOptions = req.body;
    var offset = reqOptions.currentPage * reqOptions.pageNumb;
    var limit = parseInt(reqOptions.pageNumb, 10);
    var tableName = reqOptions.tableName;
    if (reqOptions.like && reqOptions.like != "") {
        var like = JSON.parse(reqOptions.like);
    } else {
        var like = "";
    }
    if (reqOptions.wheres && reqOptions.wheres != "") {
        var wheres = JSON.parse(reqOptions.wheres);
    } else {
        var wheres = [];
    }

    var sqlOptions = {
        limit: limit,
        offset: offset,
        wheres: wheres,
        like: like,
        order: reqOptions.order,
        orderType: reqOptions.orderType,
        table: tableName
    };

    // console.log("reqOptions:", reqOptions);

    var DBCommon = new dbCommon();
    DBCommon.getAllDataList(sqlOptions).then(function (data) {
        var returnData = {
            totleNumb: data[0][0].totleNumb,
            dataList: data[1]
        }
        var result = {
            ret: 0,
            data: returnData
        };
        res.json(result);
    }, function (error) {
        console.log(error)
        var result = {
            ret: -1,
            data: error
        };
        res.json(result);
    });
});


/* post users listing. */
router.post('/addOrEditOrDelete', function (req, res, next) {
	checkCookie(req).then(function (user) {
	    var reqOptions = req.body;
	    var tableName = reqOptions.tableName;
	    var form = reqOptions.form;
	    form.updater = user;
	    var sqlOptions = {
	        tableName: tableName,
	        form: form
	    };
	    var DBCommon = new dbCommon();
	    DBCommon.addOrEditOrDelete(sqlOptions).then(function (data) {
	        var result = {
	            ret: 0,
	            data: data
	        };
	        res.json(result);
	        logger.info(tableName + '被修改， 修改人：' + user + '修改时间' + form.update_time);
	    }, function (error) {
	        var result = {
	            ret: -1,
	            data: error
	        };
	        res.json(result);
	    })
	}).catch(function (error) {
      	res.json({
            ret: -2,
            data: '请登录'
        })
    })
});


/* post users listing. */
router.post('/batchAddAtomParameter', function (req, res, next) {
	checkCookie(req).then(function (user) {
	    var reqOptions = req.body;
	    var tableName = reqOptions.tableName;
	    var form = reqOptions.form;
	    form.map(e => { return e.push(user) });
	    var sqlOptions = {
	        tableName: tableName,
	        form: form
	    };
	    var DBCommon = new dbCommon();
	    DBCommon.batchAdd(sqlOptions).then(function (data) {
	        var result = {
	            ret: 0,
	            data: data
	        };
	        res.json(result);
	        logger.info(tableName + '被修改， 修改人：' + user + '修改时间' + form.update_time);
	    }, function (error) {
	        var result = {
	            ret: -1,
	            data: error
	        };
	        res.json(result);
	    });
	}).catch(function (error) {
      	res.json({
            ret: -2,
            data: '请登录'
        })
    })
});

router.post('/batchUpdateAtomParameter', function (req, res, next) {
    var reqOptions = req.body;
    var tableName = reqOptions.tableName;
    var form = reqOptions.form;

    var sqlOptions = {
        tableName: tableName,
        form: form
    };

    // console.log("sqlOptions:", sqlOptions);

    var DBCommon = new dbCommon();
    DBCommon.batchUpdate(sqlOptions).then(function (data) {
        var result = {
            ret: 0,
            data: data
        };
        res.json(result);
    }, function (error) {
        var result = {
            ret: -1,
            data: error
        };
        res.json(result);
    });
});

router.post('/getAtomParameters', function (req, res, next) {
    var reqOptions = req.body;
    var tableName = reqOptions.tableName;
    var atomId = reqOptions.atom_id;
    var wheres = [{
        type: 1,
        key: 'atom_id',
        value: atomId
    }]
    var sqlOptions = {
        limit: 100,
        offset: 0,
        like: '',
        wheres: wheres,
        order: 'update_time',
        table: tableName
    };

    // console.log("reqOptions:", reqOptions);

    var DBCommon = new dbCommon();
    DBCommon.getAllDataList(sqlOptions).then(function (data) {
        var returnData = {
            totleNumb: data[0][0].totleNumb,
            dataList: data[1]
        }
        var result = {
            ret: 0,
            data: returnData
        };
        res.json(result);
    }, function (error) {
        var result = {
            ret: -1,
            data: error
        };
        res.json(result);
    });
})

router.post('/getDataById', function (req, res, next) {
    var reqOptions = req.body;
    var tableName = reqOptions.tableName;
    var id = reqOptions.id;
    var wheres = [{
        type: 1,
        key: 'id',
        value: id
    }]
    var sqlOptions = {
        wheres: wheres,
        table: tableName
    }
    //console.log("reqOptions:", reqOptions);
    var DBCommon = new dbCommon();
    DBCommon.getDataById(sqlOptions).then(function (data) {
        var returnData = {};
        if (data.length > 0) {
            returnData = data[0];
        }
        var result = {
            ret: 0,
            data: returnData
        };
        res.json(result);
    }, function (error) {
        var result = {
            ret: -1,
            data: error
        };
        res.json(result);
    });
})
router.post('/delete', function (req, res, next) {
	checkCookie(req).then(function (user) {
	    var reqOptions = req.body;
	    var tableName = reqOptions.tableName;
	    var id = reqOptions.id;
	    var time = new Date();
	    var wheres = [{
	        type: 1,
	        key: 'id',
	        value: id
	    }]
	    var sqlOptions = {
	        wheres: wheres,
	        table: tableName
	    }
	    var DBCommon = new dbCommon();
	    DBCommon.delete(sqlOptions).then(function (data) {
	        var result = {
	            ret: 0,
	            data: data
	        };
	        res.json(result);
	        logger.info(tableName + '被修改， 删除人：' + user + '删除时间' + time);
	    }, function (error) {
	        var result = {
	            ret: -1,
	            data: error
	        };
	        res.json(result);
	    })
	}).catch(function (error) {
      	res.json({
            ret: -2,
            data: '请登录'
        })
    })
})
router.post('/addBack', function (req, res, next) {
	checkCookie(req).then(function (user) {
	    var reqOptions = req.body;
	    var tableName = reqOptions.tableName;
	    var id = reqOptions.id;
	    var time = new Date();
	    var wheres = [{
	        type: 1,
	        key: 'id',
	        value: id
	    }]
	    var sqlOptions = {
	        wheres: wheres,
	        table: tableName
	    }
	    var DBCommon = new dbCommon();
	    DBCommon.addBack(sqlOptions).then(function (data) {
	        var result = {
	            ret: 0,
	            data: data
	        };
	        res.json(result);
	        logger.info(tableName + '被生效， 生效人：' + user + '生效时间' + time);
	    }, function (error) {
	        var result = {
	            ret: -1,
	            data: error
	        };
	        res.json(result);
	    })
	}).catch(function (error) {
      	res.json({
            ret: -2,
            data: '请登录'
        })
    })
})
router.post('/pass', function (req, res, next) {
    var reqOptions = req.body;
    var tableName = reqOptions.tableName;
    var id = reqOptions.id;
    var wheres = [{
        type: 1,
        key: 'id',
        value: id
    }]
    var sqlOptions = {
        wheres: wheres,
        table: tableName
    }
    //console.log("reqOptions:", reqOptions);
    var DBCommon = new dbCommon();
    DBCommon.pass(sqlOptions).then(function (data) {
        var result = {
            ret: 0,
            data: data
        };
        res.json(result);
    }, function (error) {
        var result = {
            ret: -1,
            data: error
        };
        res.json(result);
    });
})
router.post('/batchDelete', function (req, res, next) {
	checkCookie(req).then(function (user) {
	    var reqOptions = req.body;
	    var tableName = reqOptions.tableName;
	    var ids = reqOptions.ids;
	    // ids = ids.toString();
	    var sqlOptions = {
	        ids: ids,
	        table: tableName
	    }
	    //console.log("reqOptions:", reqOptions);
	    var DBCommon = new dbCommon();
	    DBCommon.batchDelete(sqlOptions).then(function (data) {
	        var result = {
	            ret: 0,
	            data: data
	        };
	        res.json(result);
	    }, function (error) {
	        var result = {
	            ret: -1,
	            data: error
	        };
	        res.json(result);
	    });
	}).catch(function (error) {
      	res.json({
            ret: -2,
            data: '请登录'
        })
    })
})
router.post('/batchPass', function (req, res, next) {
    var reqOptions = req.body;
    var tableName = reqOptions.tableName;
    var ids = reqOptions.ids;
    // ids = ids.toString();
    var sqlOptions = {
        ids: ids,
        table: tableName
    }
    //console.log("reqOptions:", reqOptions);
    var DBCommon = new dbCommon();
    DBCommon.batchPass(sqlOptions).then(function (data) {
        var result = {
            ret: 0,
            data: data
        };
        res.json(result);
    }, function (error) {
        var result = {
            ret: -1,
            data: error
        };
        res.json(result);
    });
})
router.post('/deleteByParams', function (req, res, next) {
    var reqOptions = req.body;
    var tableName = reqOptions.tableName;
    var params = reqOptions.params;
    var wheres = []
    for (var key in params) {
        if (params.hasOwnProperty(key)) {
            wheres.push({
                type: 1,
                key: key,
                value: params[key]
            })
        }
    }
    var sqlOptions = {
        wheres: wheres,
        table: tableName
    }
    // console.log("reqOptions:", reqOptions);
    var DBCommon = new dbCommon();
    DBCommon.deleteByParams(sqlOptions).then(function (data) {
        var result = {
            ret: 0,
            data: data
        };
        res.json(result);
    }, function (error) {
        var result = {
            ret: -1,
            data: error
        };
        res.json(result);
    });
})
router.post('/getPreviewArticle', function (req, res, next) {
    var reqOptions = req.body;
    var form = reqOptions.form;
    Observer.clear();
    ArticleCategory.preview(form)
        .then(function (ret) {
            var result = {
                ret: 0,
                data: ret
            };
            Observer.clear();
            res.json(result);
        }).catch(function (err) {
            var result = {
                ret: -1,
                data: err.message
            };
            Observer.clear();
            res.json(result);
        })

})
router.post('/getPreviewPhrase', function (req, res, next) {
    var reqOptions = req.body;
    var form = reqOptions.form;
    var phrase = new Phrase();
    phrase.template = form.template;
    Observer.clear();
    phrase.getContent().then(function () {
        var result = {
            ret: 0,
            data: phrase.content
        };
        Observer.clear();
        res.json(result);
    }).catch(function (err) {
        var result = {
            ret: -1,
            data: err.message
        };
        Observer.clear();
        res.json(result);
    })

})
router.post('/getPreviewParagraph', function (req, res, next) {
    var reqOptions = req.body;
    var form = reqOptions.form;
    Observer.clear();
    var paragraph = new Paragraph();
    paragraph.template = form.template;
    paragraph.phrases = JSON.parse(form.template);

    paragraph.getContent()
        .then(function (ret) {
            var result = {
                ret: 0,
                data: paragraph.content
            };
            Observer.clear();
            res.json(result);
        }).catch(function (error) {
//          console.log(error)
            var result = {
                ret: -1,
                data: error.message
            };
            Observer.clear();
            res.json(result);
        })

})
router.post('/getOpreators', function (req, res, next) {
    var list = [];
    for (const key in Opreators) {
        if (Opreators.hasOwnProperty(key)) {
            let item = {};
            item.label = key;
            if (key.indexOf('(') > 0) {
                item.variable = true;
            }
            //console.log(key)
            if (/\d/.test(key)) {} else {
                list.push(item);
            }
            if (key == "fixed2") {
            	list.push(item);
            }
        }
    }

    var result = {
        ret: 0,
        data: list
    }
    res.json(result);
})

router.post('/publishSchedule', function (req, res, next) {
    var reqOptions = req.body;
    var articleId = reqOptions.form.id;
    var time = reqOptions.form.time;
    Timer.startSchedule(time, articleId);
    var result = {
        ret: 0
    }
    res.json(result);
})

router.post('/publish', function (req, res, next) {
    var reqOptions = req.body;
    var ids = reqOptions.ids;
    var cssStyles = `.xg_table_wrapper{ width: 100%; overflow-x: auto;}
      .xg_table_wrapper::-webkit-scrollbar { height:6px;}
      .xg_table_wrapper::-webkit-scrollbar-track { background-color: #f0f0f0;  border-radius: 3px;}
      .xg_table_wrapper::-webkit-scrollbar-thumb { border-radius: 3px; background:rgba(0,0,0,0.3); }
      .xg_table_wrapper::-webkit-scrollbar-thumb:window-inactive { background:rgba(0,0,0,0.1);}
      .xg_table_wrapper table{ font-size: 14px; width: 100%;}
      .xg_table_wrapper th{ border: 1px #e4e4e4 solid; border-collapse: collapse; padding: 8px; word-break: break-all; background-color: #f2f1ef; vertical-align: middle; font-weight: bold; }
      .xg_table_wrapper td{ border: 1px #e4e4e4 solid; border-collapse: collapse; padding: 8px; word-break: break-all;}
      .pc_client .xg_table_wrapper th{background-color:#333}
      .xg_table_wrapper th,
      .xg_table_wrapper td{ min-width: 75px; vertical-align: middle; }`;
    if (typeof ids == 'string') {
        ids = ids.split(',');
    }
    if (ids.length == 0) {
        res.json({
            ret: -1,
            msg: 'news ids is empty'
        })
    } else {
        var DBCommon = new dbCommon();
        DBCommon.executeMysql({
            sql: 'select * from news where id in ?',
            params: [
                [ids]
            ]
        }).then(function (result) {
            var promiseArrs = [];
            result.forEach(item => {
                let param = {
                    stNewsDesc: {
                        sTitle: item.title,
                        sContent: item.content,
                        sStyle: cssStyles,
                        vtTagInfo: [{
                            eAttiType: 3,
                            sTagName: '中性'
                        }],
                        iPublish: parseInt(Date.now() / 1000)
                    },
                    eNewsTable: 9,
                    eDbSourceId: 11,
                    sSourceId: (item.id + 10001).toString(),
                    eNewsUniKey: 3 //根据_id, db_source_id去重

                }
                if (item.code && item.sec_name) {
                    param.stNewsDesc.sDtSecCode = item.code;
                    param.eNewsTable = 1;
                    param.stNewsDesc.vtRelaStock = [{
                        sDtSecCode: item.code,
                        sCHNShortName: item.sec_name
                    }]
                }
                console.log(param.stNewsDesc.iPublish + '_' + param.sSourceId + '_11_1');
                promiseArrs.push(Publish.post(param, item.id));
            })
            Promise.all(promiseArrs).then(function (result) {
                res.json({
                    ret: 0,
                    msg: 'publish success'
                })

            }).catch(function (err) {
                console.log(err)
                res.json({
                    ret: -1,
                    msg: 'publish fail'
                })
            })
        }).catch(function (err) {
            res.json({
                ret: -1,
                msg: err.message || 'query news error'
            })
        })
    }
})

router.post('/compile', function (req, res, next) {
	checkCookie(req).then(function (user) {
	    var reqOptions = req.body;
	    var tableName = reqOptions.tableName;
	    var id = reqOptions.id;
	    var force = reqOptions.force;
	    var articleCategory = new ArticleCategory(id);
	    articleCategory.init().then(function () {
	        if (force) {
	            Timer.compileArticleCategory(articleCategory, {
	                force: true
	            })
		      	res.json({
		            ret: 0
		        })
	        } else {
	            Timer.resolveYinHeArticle(articleCategory, null).then(function (msg) {
			      	res.json({
			            ret: 0,
			            data: msg
			        })
				}).catch(function (error) {
			      	res.json({
			            ret: -1,
			            data: error.message
			        })
			    })
	        }
	    })
	}).catch(function (error) {
      	res.json({
            ret: -2,
            data: '请登录'
        })
    })
})
router.post('/getSingleStockPreviewArticle', function (req, res, next) {
    var reqOptions = req.body;
    var form = reqOptions.form;
    var id = form.articleId;
    var options = {
        dt_code: form.dt_code,
        date: form.date,
        name: form.name
    }
    Observer.clear();
    var articleCategory = new ArticleCategory(id);
    articleCategory.init().then(function () {
        Timer.compileArticleCategoryBySingleStock(articleCategory, options)
            .then(function (ret) {
                Observer.clear();
                var result = {
                    ret: 0,
                    data: ret
                };
                res.json(result);
            }).catch(function (err) {
                var result = {
                    ret: -1,
                    data: err
                };
                Observer.clear();
                res.json(result);
            })
    })
    // ArticleCategory.previewSingleStock(form)
    //     .then(function (ret) {
    //         var result = {
    //             ret: 0,
    //             data: ret
    //         };
    //         Observer.clear();
    //         res.json(result);
    //     }).catch(function (err) {
    //         var result = {
    //             ret: -1,
    //             data: err
    //         };
    //         Observer.clear();
    //         res.json(result);
    //     })

})

//router.post('/change', function (req, res, next) {
//  var body = req.body;
//  var type = req.query.type;
//  console.log('type: ' + type);
//  console.log(JSON.stringify(body));
//  var result = {
//      ret: 0,
//      data: null
//  };
//  let chageType;
//  if (type == 0) {
//      chageType = body.iTransType;
//  }
//  if (type == 1) {
//      chageType = body.vList[0].eChangeType;
//  }
//  var DBCommon = new dbCommon();
//  let wheres = [{
//      type: 1,
//      key: 'category',
//  }]
//  let sqlOptions = {
//      wheres: wheres,
//      table: 'article'
//  }
//  let options = {};
//  switch (chageType) {
//      // 板块涨停
//      case 1:
//          wheres[0].value = 16;
//          options = {
//              plate_code: body.sPlateCode
//          }
//          break;
//          // 板块跌停
//      case 2:
//          wheres[0].value = 15;
//          options = {
//              plate_code: body.sPlateCode
//          }
//          break;
//          // 个股大涨
//      case 3:
//          wheres[0].value = 17;
//          options = {
//              sec_code: body.vList[0].sSecCode
//          }
//          break;
//          // 个股大跌
//      case 4:
//          wheres[0].value = 12;
//          options = {
//              sec_code: body.vList[0].sSecCode
//          }
//          break;
//          // 个股涨停
//      case 5:
//          wheres[0].value = 19;
//          options = {
//              sec_code: body.vList[0].sSecCode
//          }
//          break;
//          // 个股跌停
//      case 6:
//          wheres[0].value = 18;
//          options = {
//              sec_code: body.vList[0].sSecCode
//          }
//          break;
//      default:
//          break;
//  }
//  if (wheres[0].value) {
//      DBCommon.getDataById(sqlOptions).then(function (data) {
//          let articleCategorys = data;
//          //console.log(JSON.stringify(data))
//          if (articleCategorys.length > 0) {
//              let i = 0;
//              let compile = function () {
//                  if (i < articleCategorys.length) {
//                      let id = articleCategorys[i].id;
//                      let articleCategory = new ArticleCategory(id);
//                      articleCategory.init().then(function () {
//                          Timer.compileArticleCategory(articleCategory, options);
//                          i++;
//                          compile();
//                      })
//                  }
//              }
//              compile();
//          }
//          res.json(result);
//      }).catch(function (err) {
//          result.ret = -1;
//          result.msg = err.message;
//          res.json(result);
//      })
//  } else {
//      res.json(result);
//  }
//})

router.post('/change', function (req, res, next) {
    var body = req.body;
    let tar = body.vList[0];
    var type = body.iType;
    console.log('个股异动触发' + type);
    console.log('个股异动请求参数',JSON.stringify(body));
    var result = {
        ret: 0,
        data: null
    };
    let chageType;
    if (type == 0) {
        chageType = body.iTransType;
    }
    if (type == 1) {
        chageType = body.vList[0].eChangeType;
    }
    var DBCommon = new dbCommon();
    let wheres = [{
        type: 1,
        key: 'category',
    }]
    let sqlOptions = {
        wheres: wheres,
        table: 'article'
    }
    let options = {};
    let name = '';
    let content = '';
    switch (chageType) {
        // 板块涨停
        case 1:
            wheres[0].value = 16;
            options = {
                plate_code: body.sPlateCode
            }
            break;
            // 板块跌停
        case 2:
            wheres[0].value = 15;
            options = {
                plate_code: body.sPlateCode
            }
            break;
            // 个股大涨
        case 3:
            wheres[0].value = 17;
            options = {
                sec_code: body.vList[0].sSecCode
            };
            name = "个股异动上涨";
            content = `<div><p>【<span>${tar.sSecName.replace(/\s*/g,"")}急速拉升</span>】<span>${timestampToTime(tar.iTime)}</span>, <span>${tar.sSecName}急速拉升，5分钟内</span><span>${tar.sMsg}</span>, 报<span>${tar.fNow}</span>元。</p></div>`
            break;
            // 个股大跌
        case 4:
            wheres[0].value = 12;
            options = {
                sec_code: body.vList[0].sSecCode
            };
            name = "个股异动下跌";
            content = `<div><p>【<span>${tar.sSecName.replace(/\s*/g,"")}急速下跌</span>】<span>${timestampToTime(tar.iTime)}</span>, <span>${tar.sSecName}急速下跌，5分钟内</span><span>${tar.sMsg}</span>, 报<span>${tar.fNow}</span>元。</p></div>`
            break;
            // 个股涨停
        case 5:
            wheres[0].value = 19;
            options = {
                sec_code: body.vList[0].sSecCode
            };
            name = "个股异动涨停";
            content = `<div><p>【<span>${tar.sSecName.replace(/\s*/g,"")}涨停</span>】<span>${timestampToTime(tar.iTime)}</span>, <span>${tar.sSecName}</span>上涨<span>${tar.fUpPct}</span>%, 报<span>${tar.fNow}</span>元。</p></div>`
            break;
            // 个股跌停
        case 6:
            wheres[0].value = 18;
            options = {
                sec_code: body.vList[0].sSecCode
            };
            name = "个股异动跌停";
            content = `<div><p>【<span>${tar.sSecName.replace(/\s*/g,"")}跌停</span>】<span>${timestampToTime(tar.iTime)}</span>, <span>${tar.sSecName}</span>涨跌幅为<span>${tar.fUpPct}</span>%, 报<span>${tar.fNow}</span>元。</p></div>`
            break;
        default:
            break;
    }
    if (wheres[0].value) {
        DBCommon.getDataById(sqlOptions).then(function (data) {
            let articleCategorys = data;
            console.log(JSON.stringify(data))
            if (articleCategorys.length > 0) {
                let i = 0;
                let compile = function () {
                    if (i < articleCategorys.length) {
                        let id = articleCategorys[i].id;
                        let articleCategory = new ArticleCategory(id);
                        articleCategory.init().then(function () {
                    		if(articleCategory.status == 1){
    			              	DBCommon.addOrEditOrDelete({
					                form: {
					                  'name': name,
					                  'category': articleCategory.category,
					                  'channel': articleCategory.channel,
					                  'code': '',
					                  'sec_name': '',
					                  'title': '',
					                  'content': content,
					                  'verified': 1
					                },
					                tableName: 'news'
				              	}).then(function (result) {
					                var news_id = result.insertId;
					                var channels = articleCategory.channel.split(',');
					                var news_channels = [];
					                for (var i = 0; i < channels.length; i++) {
					                  var channel_id = channels[i];
					                  news_channels.push([news_id, Number(channel_id), new Date()])
					                }
					                DBCommon.batchAddNewsChannel({
					                  form: news_channels,
					                  tableName: 'auto_news_channel'
					                }).then(function (result2) {
					                  logger.info('个股异动：' + name + ' generate success ');
					                  Observer.clear();
					                })
			              		})
							} else {
								logger.info('异动文章失效不编译：' + articleCategory.name + articleCategory.status)
							}
//                          Timer.compileArticleCategory(articleCategory, options);
                            i++;
                            compile();
                        })
                    }
                }
                compile();
            }
            res.json(result);
        }).catch(function (err) {
            result.ret = -1;
            result.msg = err.message;
            res.json(result);
        })
    } else {
        res.json(result);
    }
})

// 个股涨停原因揭秘
router.post('/stockRiseFallRevealed', function (req, res, next) {
    var body = req.body;
    let tar = body;
    var type = 1;
    console.log('个股涨停揭秘触发' + type);
    console.log(JSON.stringify(body));
    var result = {
        ret: 0,
        data: null
    };
    var DBCommon = new dbCommon();
    let wheres = [{
        type: 1,
        key: 'category',
    }]
    let sqlOptions = {
        wheres: wheres,
        table: 'article'
    }
    let options = {};
    let name = '';
    let content = '';
    let title = '';
    // 个股涨停揭秘
    wheres[0].value = 32;
    options = {
        sec_code: body.code
    };
    name = "个股涨停原因揭秘";
    content = `<div><p><span>${timestampToMD(tar.upTime/1000)}讯，</span><span>${tar.name}</span><span>(${tar.code})</span>今日<span>${timestampToTime(tar.upTime/1000)}</span>涨停， 报<span>${parseFloat(tar.zjcj).toFixed(2)}</span>元，封单<span>${tar.bl1}</span>手，成交量<span>${tar.cjsl}</span>手，换手率<span>${parseFloat(tar.hsl).toFixed(2)}</span>%。</p><p><span>涨停原因：</span><span>${tar.upReason}</span></p></div>`
    title = `${tar.name}:${timestampToTime(tar.upTime/1000)}涨停`
    if (wheres[0].value) {
        DBCommon.getDataById(sqlOptions).then(function (data) {
            let articleCategorys = data;
            console.log(JSON.stringify(data))
            if (articleCategorys.length > 0) {
                let i = 0;
                let compile = function () {
                    if (i < articleCategorys.length) {
                        let id = articleCategorys[i].id;
                        let articleCategory = new ArticleCategory(id);
                        articleCategory.init().then(function () {
                    		if(articleCategory.status == 1){
    			              	DBCommon.addOrEditOrDelete({
					                form: {
					                  'name': name,
					                  'category': articleCategory.category,
					                  'channel': articleCategory.channel,
					                  'code': '',
					                  'sec_name': '',
					                  'title': title,
					                  'content': content,
					                  'verified': 1
					                },
					                tableName: 'news'
				              	}).then(function (result) {
					                var news_id = result.insertId;
					                var channels = articleCategory.channel.split(',');
					                var news_channels = [];
					                for (var i = 0; i < channels.length; i++) {
					                  var channel_id = channels[i];
					                  news_channels.push([news_id, Number(channel_id), new Date()])
					                }
					                DBCommon.batchAddNewsChannel({
					                  form: news_channels,
					                  tableName: 'auto_news_channel'
					                }).then(function (result2) {
					                  logger.info('个股涨停原因揭秘：' + name + ' generate success ');
					                  Observer.clear();
					                })
			              		})
							} else {
								logger.info('个股涨停原因揭秘失效不编译：' + articleCategory.name + articleCategory.status)
							}
                            i++;
                            compile();
                        })
                    }
                }
                compile();
            }
            res.json(result);
        }).catch(function (err) {
            result.ret = -1;
            result.msg = err.message;
            res.json(result);
        })
    } else {
        res.json(result);
    }
})

// 指数异动
router.post('/indexChange', function (req, res, next) {
    var body = req.body;
    let tar = body;
    console.log('指数异动触发' );
    console.log(JSON.stringify(body));
    var plateNameList = [];
    tar.plate.forEach((item) =>{
        plateNameList.push(item.name);
    });
    // 小时分钟
    var hmStr =String(tar.hqtm);
    if(hmStr.length == 3){
        hmStr = '0' + hmStr;
    };
    var result = {
        ret: 0,
        data: null
    };
    var DBCommon = new dbCommon();
    let wheres = [{
        type: 1,
        key: 'category',
    }]
    let sqlOptions = {
        wheres: wheres,
        table: 'article'
    }
    let options = {};
    let name = '';
    let content = '';
    let title = '';
    // 指数异动category
    wheres[0].value = 33;
    options = {
        sec_code: body.code
    };
    name = "指数异动";
    content = `<div><p><span>【${hmStr.slice(0,2)}时${hmStr.slice(2,4)}分${tar.name}(${tar.code.split('.')[0]})涨幅${(tar.change*100).toFixed(2)}%】</span><span>${parseInt(String(tar.hqda).slice(4,6))}月${parseInt(String(tar.hqda).slice(6,8))}日讯，${tar.name}截至${hmStr.slice(0,2)}时${hmStr.slice(2,4)}分${tar.change > 0?'涨':'跌'}${Math.abs((tar.change*100).toFixed(2))}%，报${(tar.zjcj).toFixed(2)}点。盘面上${(plateNameList).join('、').replace(/[\(\（].*?[\)\）]/g,'')}等板块${tar.change > 0?'涨':'跌'}幅居前。沪深两市共成交${(tar.cjje/100000000).toFixed(2)}亿元。</span></p></div>`
    title = `${hmStr.slice(0,2)}时${hmStr.slice(2,4)}分${tar.name}(${tar.code.split('.')[0]})涨幅${(tar.change*100).toFixed(2)}%`
    if (wheres[0].value) {
        DBCommon.getDataById(sqlOptions).then(function (data) {
            let articleCategorys = data;
            console.log(JSON.stringify(data))
            if (articleCategorys.length > 0) {
                let i = 0;
                let compile = function () {
                    if (i < articleCategorys.length) {
                        let id = articleCategorys[i].id;
                        let articleCategory = new ArticleCategory(id);
                        articleCategory.init().then(function () {
                    		if(articleCategory.status == 1){
    			              	DBCommon.addOrEditOrDelete({
					                form: {
					                  'name': name,
					                  'category': articleCategory.category,
					                  'channel': articleCategory.channel,
					                  'code': '',
					                  'sec_name': '',
					                  'title': title,
					                  'content': content,
					                  'verified': 1
					                },
					                tableName: 'news'
				              	}).then(function (result) {
					                var news_id = result.insertId;
					                var channels = articleCategory.channel.split(',');
					                var news_channels = [];
					                for (var i = 0; i < channels.length; i++) {
					                  var channel_id = channels[i];
					                  news_channels.push([news_id, Number(channel_id), new Date()])
					                }
					                DBCommon.batchAddNewsChannel({
					                  form: news_channels,
					                  tableName: 'auto_news_channel'
					                }).then(function (result2) {
					                  logger.info('指数异动：' + name + ' generate success ');
					                  Observer.clear();
					                })
			              		})
							} else {
								logger.info('指数异动失效不编译：' + articleCategory.name + articleCategory.status)
							}
                            i++;
                            compile();
                        })
                    }
                }
                compile();
            }
            res.json(result);
        }).catch(function (err) {
            result.ret = -1;
            result.msg = err.message;
            res.json(result);
        })
    } else {
        res.json(result);
    }
})

// 板块异动
router.post('/plateChange', function (req, res, next) {
    var body = req.body;
    var plateChangeType;
    console.log('板块异动触发');
    console.log('req.body',req.body);
    console.log('typeof req.body',typeof req.body);
    console.log(JSON.stringify(body));
    var result = {
        ret: 0,
        data: null
    };
    if(body.vPlateZhangSuChangeRsp){
        var dataList = body.vPlateZhangSuChangeRsp;
        plateChangeType = 0;
    } else if(body.vPlateZhangFuChangeRsp){
        var dataList = body.vPlateZhangFuChangeRsp;
        plateChangeType = 1;
    }
    
    var bkName = dataList[0].sName.replace(/[\(\（].*?[\)\）]/g,'');
    var topStock = dataList[1]
    var stockList = dataList.slice(2);
    var stockNameList = [];
    stockList.forEach((item)=>{ stockNameList.push(item.sName + "(" + (item.fChangePtc >0 ?"+"+(item.fChangePtc *100).toFixed(2) : (item.fChangePtc *100).toFixed(2))+ "%)")});
    console.log('stockList',stockList)
    var DBCommon = new dbCommon();
    let wheres = [{
        type: 1,
        key: 'category',
    }]
    let sqlOptions = {
        wheres: wheres,
        table: 'article'
    }
    let options = {};
    let name = '';
    let content = '';
    let title = '';
    // 板块异动文章在article表的category
    wheres[0].value = 34;
    options = {
        sec_code: body.code
    };
    name = "板块异动";
    if(plateChangeType == 0){
        content = `<div><p><span>【${bkName}板块${dataList[0].fChangePtc>0?'急速上涨':'急速下跌'}】</span><span>${bkName}板块${dataList[0].fChangePtc>0?'急速上涨':'急速下跌'}，截至发稿，${topStock.sName}涨幅(${topStock.fChangePtc > 0? '+'+(topStock.fChangePtc*100).toFixed(2):(topStock.fChangePtc*100).toFixed(2)}%)，${stockNameList.join('、')}等个股${topStock.fChangePtc>0?'涨幅':'跌幅'}居前。</span></p></div>`
        title = `${bkName}板块${dataList[0].fChangePtc>0?'急速上涨':'急速下跌'}`
    } else if(plateChangeType == 1){
        content = `<div><p><span>【${bkName}板块${dataList[0].fChangePtc>0?'涨幅':'跌幅'}达${Math.abs(dataList[0].fChangePtc*100).toFixed(2)}%】</span><span>截至发稿，${bkName}板块${dataList[0].fChangePtc>0?'涨幅':'跌幅'}达${Math.abs(dataList[0].fChangePtc*100).toFixed(2)}%，${topStock.sName}涨幅(${topStock.fChangePtc > 0? '+'+(topStock.fChangePtc*100).toFixed(2):(topStock.fChangePtc*100).toFixed(2)}%)，${stockNameList.join('、')}等个股${topStock.fChangePtc>0?'涨幅':'跌幅'}居前。</span></p></div>`
        title = `${bkName}板块${dataList[0].fChangePtc>0?'涨幅':'跌幅'}达${Math.abs(dataList[0].fChangePtc*100).toFixed(2)}%`
    }
    
    if (wheres[0].value) {
        DBCommon.getDataById(sqlOptions).then(function (data) {
            let articleCategorys = data;
            console.log(JSON.stringify(data))
            if (articleCategorys.length > 0) {
                let i = 0;
                let compile = function () {
                    if (i < articleCategorys.length) {
                        let id = articleCategorys[i].id;
                        let articleCategory = new ArticleCategory(id);
                        articleCategory.init().then(function () {
                    		if(articleCategory.status == 1){
    			              	DBCommon.addOrEditOrDelete({
					                form: {
					                  'name': name,
					                  'category': articleCategory.category,
					                  'channel': articleCategory.channel,
					                  'code': '',
					                  'sec_name': '',
					                  'title': title,
					                  'content': content,
					                  'verified': 1
					                },
					                tableName: 'news'
				              	}).then(function (result) {
					                var news_id = result.insertId;
					                var channels = articleCategory.channel.split(',');
					                var news_channels = [];
					                for (var i = 0; i < channels.length; i++) {
					                  var channel_id = channels[i];
					                  news_channels.push([news_id, Number(channel_id), new Date()])
					                }
					                DBCommon.batchAddNewsChannel({
					                  form: news_channels,
					                  tableName: 'auto_news_channel'
					                }).then(function (result2) {
					                  logger.info('个股涨停原因揭秘：' + name + ' generate success ');
					                  Observer.clear();
					                })
			              		})
							} else {
								logger.info('个股涨停原因揭秘失效不编译：' + articleCategory.name + articleCategory.status)
							}
                            i++;
                            compile();
                        })
                    }
                }
                compile();
            }
            res.json(result);
        }).catch(function (err) {
            result.ret = -1;
            result.msg = err.message;
            res.json(result);
        })
    } else {

        res.json(result);
    }
})

module.exports = router;